﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using com.IronOne.BoardPACWinApp.Common;
using com.IronOne.BoardPACWinApp.Helpers;
using com.IronOne.BoardPACWinAppBO.Agenda;
using com.IronOne.BoardPACWinAppBO.Paper;
using com.IronOne.BoardPACWinAppService.Agenda;
using com.IronOne.BoardPACWinAppUtil.Enums;
using com.IronOne.BoardPACWinAppUtil.Util;

// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236

namespace com.IronOne.BoardPACWinApp.View.UserControl
{
    public sealed partial class AnnotationShareUserControl
    {
        public static AgendaItem GlobalSelectdAgendaItem;
        private readonly IAgendaService _agendaService;
        private readonly IDialogService _dialogService;
        private const string DoneTxt = "Done";
        public static event EventHandler OriginalPaperLoadingButtonClickedEvent;
        public static event EventHandler SentPapersButtonClickedEvent;
        public static event EventHandler ReceivedPapersButtonClickedEvent;

        public AnnotationShareUserControl()
        {
            InitializeComponent();
            _agendaService = new AgendaService();
            _dialogService = new DialogService();
        }


        public async void ShowPopup(AgendaItem agendaItem)
        {
            try
            {
                GlobalSelectdAgendaItem = agendaItem;
                var width = (int)(Window.Current.Bounds.Width / 3);
                if (width < Utility.GetFlyoutDefaultWidth()) width = Utility.GetFlyoutDefaultWidth();
                InnGrd.Width = Convert.ToDouble(width);
                InnGrd.Height = Window.Current.Bounds.Height;

                ContentPopup.IsOpen = true;
                ContentPopup.IsLightDismissEnabled = false;

                var stat = await CheckForAnnotations();
                if (!stat)
                {
                    ListViewErrTxt.Text = "Please annotate the paper before sharing";
                    ErrorDisplay();
                    return;
                }

                var memberList = await _agendaService.GetParticipantsListForMeeting(agendaItem.MeetingId);
                if (memberList == null || memberList.Count <= 0)
                {
                    ListViewErrTxt.Text = "No members available for sharing";
                    ErrorDisplay();
                    return;
                }
                
                var memItem = memberList.FirstOrDefault(x => x.MemberId == Global.UserId);
                if (memItem != null)
                    memberList.Remove(memItem);

                foreach (var item in memberList)
                {
                    item.ProfilePicPath = await BasePage.UpdateProfilePic(item.MemberId);
                }
                ParticipantsListView.DataContext = memberList;
                ParticipantsListView.Visibility = Visibility.Visible;
            }
            catch (Exception)
            {
                ListViewErrTxt.Text = "Member details loading process encounter an error";
                ErrorDisplay();
            }
            finally
            {
                PgbPage.Visibility = Visibility.Collapsed;
            }
        }

        public void ClosePopup()
        {
            ContentPopup.IsOpen = false;
        }

        private void ErrorDisplay()
        {
            ListViewErrTxt.Visibility = Visibility.Visible;
            ParticipantsListView.Visibility = Visibility.Collapsed;
            SelectAllPnl.Visibility = Visibility.Collapsed;

            ShareBtn.Visibility = Visibility.Collapsed;
            CancelBtn.Content = DoneTxt;
        }

        private async Task<bool> CheckForAnnotations()
        {
            try
            {
                var annotFile = await BasePage.GetAnnotationFile(GlobalSelectdAgendaItem);
                return annotFile != null;
            }
            catch (Exception)
            {
                return false;
            }
        }

        private async void ShareBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var items = ParticipantsListView.SelectedItems;
                var selectedList = items.Cast<MemberModel>().Where(item => item.IsActive == (int) BoardMemberIsActive.Active).ToList();

                if (selectedList.Count <= 0)
                {
                    await _dialogService.ShowMessage("Please select one or more members to share");
                    return;
                }

                PgbPage.Visibility = Visibility.Visible;
                var rdm = await _agendaService.UploadAnnotation(selectedList, GlobalSelectdAgendaItem);
                PgbPage.Visibility = Visibility.Collapsed;

                if (rdm.IsError)
                {
                    await _dialogService.ShowMessage(rdm.ErrorMessage);
                    return;
                }

                ClosePopup();
            }
            catch (Exception)
            {
            }
        }

        private void CancelBtn_Click(object sender, RoutedEventArgs e)
        {
            ClosePopup();
        }


        //Share
        private async void Item1_Btn_Click(object sender, RoutedEventArgs e)
        {
            #region Item1_Btn_Click

            try
            {
                ResetButtons();
                ShareBtn.Visibility = Visibility.Visible;
                CancelBtn.Content = "Cancel";
                Item1Btn.Opacity = 1;
                LastTxt.Text = "Select members";
                SelectAllPnl.Visibility = Visibility.Visible;
                ParticipantsListView.Visibility = Visibility.Visible;
                Item1Btn.Background = new SolidColorBrush(Colors.SkyBlue);

                var memberList = await _agendaService.GetParticipantsListForMeeting(GlobalSelectdAgendaItem.MeetingId);
                if (memberList == null || memberList.Count <= 0)
                {
                    ListViewErrTxt.Text = "No members available for sharing";
                    ErrorDisplay();
                }
            }
            catch (Exception)
            {
                ShareBtn.Visibility = Visibility.Collapsed;
                SelectAllPnl.Visibility = Visibility.Collapsed;
                ParticipantsListView.Visibility = Visibility.Collapsed;
                ListViewErrTxt.Text = "Sharing encounter an error";
                ErrorDisplay();
            }
            finally
            {
                PgbPage.Visibility = Visibility.Collapsed;
            }

            #endregion
        }

        //Received
        private async void Item2_Btn_Click(object sender, RoutedEventArgs e)
        {
            #region Item2_Btn_Click

            try
            {
                ResetButtons();
                Item2Btn.Opacity = 1;
                LastTxt.Text = "Received papers";
                Item2Btn.Background = new SolidColorBrush(Colors.SkyBlue);
                ReceivedListView.Visibility = Visibility.Visible;

                var models = await _agendaService.GetPaperVersionReceivedByUser(GlobalSelectdAgendaItem.Id);
                ReceivedListView.ItemsSource = models;

                if (models == null || models.Count <= 0)
                {
                    ReceivedListView.Visibility = Visibility.Collapsed;
                    ListViewErrTxt.Text = "No received annotations";
                    ErrorDisplay(); 
                }
            }
            catch (Exception)
            {
                ReceivedListView.Visibility = Visibility.Collapsed;
                ListViewErrTxt.Text = "Received annotations encounter an error";
                ErrorDisplay();
            }
            finally
            {
                PgbPage.Visibility = Visibility.Collapsed;
            }
            
            #endregion
        }

        //Sent
        private async void Item3_Btn_Click(object sender, RoutedEventArgs e)
        {
            #region Item3_Btn_Click

            try
            {
                ResetButtons();
                Item3Btn.Opacity = 1;
                LastTxt.Text = "Sent papers";
                SentListView.Visibility = Visibility.Visible;
                Item3Btn.Background = new SolidColorBrush(Colors.SkyBlue);

                var models = await _agendaService.GetPaperVersionSentByUser(GlobalSelectdAgendaItem.Id);
                SentListView.ItemsSource = models;

                if (models == null || models.Count <= 0)
                {
                    ReceivedListView.Visibility = Visibility.Collapsed;
                    ListViewErrTxt.Text = "No sent annotations";
                    ErrorDisplay();
                }
            }
            catch (Exception)
            {
                SentListView.Visibility = Visibility.Collapsed;
                ListViewErrTxt.Text = "Sent annotations encounter an error";
                ErrorDisplay();
            }
            finally
            {
                PgbPage.Visibility = Visibility.Collapsed;
            }

            #endregion
        }

        //Original
        private void Item4_Btn_Click(object sender, RoutedEventArgs e)
        {
            #region Item4_Btn_Click

            try
            {
                ResetButtons();
                Item4Btn.Opacity = 1;
                LastTxt.Text = "Original paper";
                Item4Btn.Background = new SolidColorBrush(Colors.SkyBlue);

                OriginalPaperLoading_ButtonClick();
            }
            catch (Exception)
            {
                ListViewErrTxt.Text = "Original paper viewing encounter an error";
                ErrorDisplay();
            }
            finally
            {
                PgbPage.Visibility = Visibility.Collapsed;
            }
            #endregion
        }

        private void ResetButtons()
        {
            PgbPage.Visibility = Visibility.Visible;
            ShareBtn.Visibility = Visibility.Collapsed;
            CancelBtn.Content = DoneTxt;
            ListViewErrTxt.Text = "";

            Item1Btn.Opacity = 0.7;
            Item2Btn.Opacity = 0.7;
            Item3Btn.Opacity = 0.7;
            Item4Btn.Opacity = 0.7;

            SelectAllPnl.Visibility = Visibility.Collapsed;
            ParticipantsListView.Visibility = Visibility.Collapsed;
            ReceivedListView.Visibility = Visibility.Collapsed;
            SentListView.Visibility = Visibility.Collapsed;

            Item1Btn.Background = new SolidColorBrush(Colors.Transparent);
            Item2Btn.Background = new SolidColorBrush(Colors.Transparent);
            Item3Btn.Background = new SolidColorBrush(Colors.Transparent);
            Item4Btn.Background = new SolidColorBrush(Colors.Transparent);
        }


        private void SelectAll_Btn_Click(object sender, RoutedEventArgs e)
        {
            if (SelectAllChk.IsChecked != null && (bool) SelectAllChk.IsChecked)
                SelectAllChk.IsChecked = false;
            else
            {
                SelectAllChk.IsChecked = true;
                ParticipantsListView.SelectAll();
            }
        }

        private void SelectAll_Chk_Checked(object sender, RoutedEventArgs e)
        {
            ParticipantsListView.SelectAll();
        }

        private void SelectAll_Chk_Unchecked(object sender, RoutedEventArgs e)
        {
            ParticipantsListView.SelectedIndex = -1;
        }


        private void OriginalPaperLoading_ButtonClick()
        {
            if (OriginalPaperLoadingButtonClickedEvent != null)
            {
                OriginalPaperLoadingButtonClickedEvent(this, EventArgs.Empty);
            }
        }

        private void SentPapers_ButtonClick(PaperModel pModel)
        {
            if (SentPapersButtonClickedEvent != null)
            {
                SentPapersButtonClickedEvent(pModel, EventArgs.Empty);
            }
        }

        private void ReceivedPapers_ButtonClick(PaperModel pModel)
        {
            if (ReceivedPapersButtonClickedEvent != null)
            {
                ReceivedPapersButtonClickedEvent(pModel, EventArgs.Empty);
            }
        }

        private void SentListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var paperModel = (PaperModel)SentListView.SelectedItem;
            SentPapers_ButtonClick(paperModel);
        }

        private void ReceivedListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var paperModel = (PaperModel)ReceivedListView.SelectedItem;
            ReceivedPapers_ButtonClick(paperModel);
        }
    }
}